﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace eslib.nnp5.AT
{
    /// <summary>
    /// AT指令拆分
    /// </summary>
    public class ATParamSplitor
    {
        Regex regSimple = new Regex(@"^\w+$");
        Regex regQuestion = new Regex(@"^\w+\?$");
        Regex regNormal = new Regex(@"^\w+=([^,]+,)*[^,]+$");

        /// <summary>
        /// 拆分指令,格式不正确将引发ATException
        /// </summary>
        /// <param name="at">传入的at没有AT+头和\r\n结尾</param>
        /// <returns></returns>
        public ATResult Split(string at)
        {
            //分析AT类型
            if (regSimple.IsMatch(at)) return simpleSplit(at);
            if (regQuestion.IsMatch(at)) return questionSplit(at);
            if (regNormal.IsMatch(at)) return normalSplit(at);

            throw new ATException("AT指令格式不正确");
        }


        private ATResult normalSplit(string at)
        {
            ATResult ret = new ATResult();

            //已经过正则表达式判断，因此可以直接用等号，逗号拆分
            //FUCK="charme",123,3.1415      
            string[] cmdprms = at.Split('=');
            ATParam cmd = new ATParam(ATParmaType.Command, cmdprms[0]);
            ret.Params.Add(cmd);

            string[] prms = cmdprms[1].Split(',');
            foreach (var prm in prms)
            {
                //移除双引号
                string val = prm.Replace("\"", "");
                ATParam p = new ATParam(ATParmaType.Normal, val);
                ret.Params.Add(p);
            }

            return ret;
        }

        private ATResult questionSplit(string at)
        {
            ATResult ret = new ATResult();

            //FUCK?
            ATParam cmd = new ATParam(ATParmaType.Command, at.Replace("?", ""));
            ATParam question = new ATParam(ATParmaType.Question, "");
            ret.Params.Add(cmd);
            ret.Params.Add(question);

            return ret;
        }

        private ATResult simpleSplit(string at)
        {
            ATResult ret = new ATResult();

            //FUCK
            ret.Params.Add(new ATParam(ATParmaType.Command, at));

            return ret;
        }
    }
}
